import guiCommon

from world.wineObjects import Tasting
from world.bottle import Bottle

from wineEdit import *

import world.wineTasting as wineTasting

from kivyext.simplepopup import SimplePopup
from kivy.uix.stacklayout import StackLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.properties import BooleanProperty

class TastingCompactButton(Button):
    wordPressed = []
    editor = None
    #category = 
    
    def on_press(self, *l):
        self.wordPressed.append( self.text)
        t = self.editor.txtinput.text
        self.editor.txtinput.text = t+', '+self.text if t else self.text
        

class WordStack(BoxLayout):
    instanceDic = dict(wineTasting.TastingDescriptions)

    parentPopup = ObjectProperty(None)
    stack = ObjectProperty(None)

    background_colors = []
    
    def __init__(self, words=[], **kargs):
        super(WordStack, self).__init__(**kargs)
        self.add_words(words,color_i=0)
        
    def add_words(self, words, color_i):
        stack = self.stack
        bg = self.background_colors[color_i]
        for w in words:
            b = TastingCompactButton(text=w, size_hint=(None,None))
            stack.add_widget( b )
            b.background_color =bg
            #print ' set word  ',w, ' color ', b.background_color, bg

    
    @staticmethod
    def getStack(holder):
        if WordStack.background_colors == []:
           dummy = TastingCompactButton()
           bg = [ list(dummy.background_color), list(dummy.background_color) ]
           bg[0][-1] = 0 # full transparent
           bg[1][-1] = 0.1 # not full transparent
           WordStack.background_colors = bg
           
        ws = WordStack.instanceDic.get(holder.attKey)
        if isinstance(ws, list):
            r = (float(theTastingEditWindow.width) / Window.width + 1)/2.
            
            wstack = WordStack()
            if isinstance(ws[0], str):
                wstack.add_words(ws)
                nw = len(ws)
            else:
                # this must be  a list of list of strings (concatenation of several tasting aspects)
                nw=0
                for i,wl in enumerate(ws) :                    
                    wstack.add_words(wl, i%2)
                    nw += len(wl)

            height = max(200, (nw/3+2)*32)
            pop = SimplePopup( content = [wstack] , size=(200,height), size_hint=(None,None), pos_hint = {'x':r,'y':0.5}, _anim_alpha=0.)
            wstack.parentPopup = pop            
            #pop.bind( on_dismiss = holder.fillFromWS)
            WordStack.instanceDic[holder.attKey] = wstack
            ws = wstack
        ## else:
        ##     for w in ws.stack.children:
        ##         print '  uuuuu ', w.background_color
        return ws
        

class AttributeTextButton(AttributeEdit):
    edition_parameters = [('multiline',False) , ('TextInputClass',CompactTextInput) ,'text']

    def buildEditWid(self):
        TextInputClass = self._edition_dict.pop('TextInputClass')
        self.txtinput = TextInputClass(size_hint=(0.9,1),**self._edition_dict)
        self.bt = guiCommon.LeVinButton(text='+', bold=True, size_hint=(0.1,1))
        self.bt.size_hint = (0.1,1)
        self.bt.bind( on_press = self.open_WS)
        box = BoxLayout(orientation='horizontal')
        box.add_widget(self.txtinput)
        box.add_widget(self.bt)        
        return box

    def fromEditedObject(self, bottle):
        text = getattr(bottle, self.attKey)
        if text is not None:
            self.txtinput.text = text 

    def toEditedObject(self, bottle):
        text = self.txtinput.text
        #print ' editing ', bottle, self.attKey, text
        if text != '':
            setattr( bottle, self.attKey, text)

    def open_WS(self, *l):
        ws = WordStack.getStack(self)
        TastingCompactButton.editor = self
        self.txtinput.focus = True
        ws.parentPopup.open()
        

class RateEdit(SpinBoxEdit):        
    def toEditedObject(self, tasting):
        v = self.editWid.value
        if v>=0 :
            tasting.rate = v
            #setattr( bottle, self.attKey, v)

class TastingEditWidget(EditWidgetBase,BoxLayout):

    advanced_mode = BooleanProperty(False)

    editorList = ObjectProperty(None)

    _drinkOneBottle = False
    def __init__(self, **kargs):
        super(TastingEditWidget,self).__init__(**kargs)
        self.editorList.DefaultWidClass = LeVinTreeLabel
        self.buildWidgetList()


    def buildWidgetList(self):
        #print self.editorList
        editWidgetList = [
            DateEdit("date", text=date_today.strftime(dateformat)),
            RateEdit("rate", value=2),
            
            ]
        _orderedAtt = list(wineTasting.OrderedTastingAtt.iterAll())
        editWidgetListAtt =  [ 
            #AttributeText(a,ad) for a, ad in wineTasting.OrderedTastingAtt.iterAll()
            AttributeTextButton(a,ad) for a, ad in _orderedAtt[:-1]
        ]
        for i,att in enumerate(editWidgetListAtt):
            if i in [3,7,13,14]:
                # categories
                att.txtinput.multiline = True
            else:
                att.is_visible = self.advanced_mode
        #print _orderedAtt
        a,ad = _orderedAtt[-1]
        editWidgetListAtt += [ AttributeText(a,ad ) ]
        
        for a in editWidgetList+editWidgetListAtt:
            self.editorList.add_entry(a)
        self.current_bottle = None
        self.editWidgetListAtt =  editWidgetListAtt

    def switchMode(self,*l):
        for i,att in enumerate(self.editWidgetListAtt):
            if i not in [3,7,13,14]:
                att.is_visible = self.advanced_mode
        
    def start_edit_tasting(self,ev,tasting, drinkOneBottle=False):
        #print ' CCCCCCCCC ------------------ ',ev, tasting, drinkOneBottle
        if tasting is None:
            return
        elif isinstance(tasting, Bottle) :
            bottle = tasting
            tasting = Tasting()
            tasting.bottle = bottle
            if not bottle.tastings:                
                bottle.tastings = [ tasting ]                
            else:
                bottle.tastings += [ tasting ]
            self.current_bottle= tasting # replace current_bottle by tasting                
        else:
            # not sure this ever gets called ...
            bottle = tasting.bottle
            self.current_bottle= bottle

        theTastingEditWindow.content.fromEditedObject(tasting)
        theTastingEditWindow.open()
        self._drinkOneBottle = drinkOneBottle

    def end_edit_tasting(self,ev ,tasting,save=False):
        if not save:
            theTastingEditWindow.dismiss()
            return

        self.toEditedObject(tasting) # this calls toEditedObject from all sub-widgets of self
        print "xxxx", tasting, "  -> ",tasting.bottle, tasting, tasting.rate
        tasting.bottle.updateRate()        
        if self._drinkOneBottle:
            tasting.bottle.numInStock -= 1
            self._drinkOneBottle = False
        tasting.bottle.requestSaveContent()
        guiCommon.commonEvents.dispatch('on_bottle_edited',tasting.bottle) # rate might have changed !
        tasting.bottle.update_widget() # needs a direct call (bottles don't listen to commonEvents)
        #print 'end_edit_tasting ', tasting, tasting.bottle
        guiCommon.commonEvents.dispatch('on_tasting_edited', tasting)
        theTastingEditWindow.dismiss()




from kivy.factory import Factory
for cls in [ TastingEditWidget, TastingCompactButton, WordStack]:
    Factory.register(cls.__name__, cls=cls)
from kivy.lang import Builder
guiCommon.load_kv_file('tastingEdit.kv')


theTastingEditWindow = guiCommon.LeVinPopup(title=_('Edit Tasting'), size_hint=(None,None), size=(500,500))
theTastingEditWindow.content =  TastingEditWidget()

guiCommon.commonEvents.bind(on_start_edit_tasting = theTastingEditWindow.content.start_edit_tasting    )
guiCommon.commonEvents.bind(on_end_edit_tasting   = theTastingEditWindow.content.end_edit_tasting    )
